using System;
using System.Linq;
using System.Reflection;
using Churchtoolkit.DataAccess.Common;
using Churchtoolkit.Utils.Authentication;
using Churchtoolkit.Utils.Composit;
using Churchtoolkit.Utils.EmailProvider;
using Churchtoolkit.Utils.ErrorProvider;
using Churchtoolkit.Web.Shell.Services;
using Microsoft.Practices.Unity;
using Utils.EventAggregator;
using Churchtoolkit.Utils.RulesManager;
using Churchtoolkit.Utils.BackgroundTasks;

namespace Churchtoolkit.Web.Shell
{
    public class ShellModuleInitilizer : ModuleInitilizerBase
    {
        public override void OnInitilizeContainer(IUnityContainer container)
        {
            container.RegisterInstance<IEventAggregator>(new EventAggregator());
            //------------------------------------------------------
            Type baseOfAllRepositories = typeof (IRepository);
            Type[] allTypes = Assembly.GetAssembly(baseOfAllRepositories).GetTypes();

            foreach (Type repository in allTypes.Where(baseOfAllRepositories.IsAssignableFrom))
            {
                if (repository.IsAbstract || repository.IsGenericType)
                    continue;

                container.RegisterInstance(repository,
                                           Activator.CreateInstance(repository, Constants.DefaultConnectionString));
            }
            //------------------------------------------------------------------
            //TODO: this line must be moved to Inilitize Service
            container.RegisterType<IBackgroundTask, RulesExecuter>("rules", new ContainerControlledLifetimeManager());
            container.RegisterType<IBackgroundTask, Churchtoolkit.Web.Shell.Services.Bootstrappers.RegistrerdUserMailBootstraperTask>("registerUserEmailTask", new ContainerControlledLifetimeManager());
            //------------------------------------------------------------------
            container.RegisterType<IErrorProvider, ErrorService>(new ContainerControlledLifetimeManager());
            container.RegisterType<IEmailProvider, EmailService>(new ContainerControlledLifetimeManager());
            container.RegisterType<IAuthentication, AuthenticationService>(new ContainerControlledLifetimeManager());
            container.RegisterType<IRulesManager, RulesManager>(new ContainerControlledLifetimeManager());
        }
    }
}